package com.zrq.jwtdemo.author.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrq.jwtdemo.author.dto.result.LoginResult;
import com.zrq.jwtdemo.author.mapper.UsersMapper;
import com.zrq.jwtdemo.author.model.Users;
import com.zrq.jwtdemo.core.constant.Constant;
import com.zrq.jwtdemo.core.exception.AppException;
import com.zrq.jwtdemo.author.dto.request.LoginRequest;
import com.zrq.jwtdemo.core.utils.JwtUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:
 * @CreateDate: 2020/12/19
 * @Version: 类说明：登录业务层
 */
@Service
@AllArgsConstructor
@Validated
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class LoginService {

    private final JwtUtils jwtUtils;

    private final UsersMapper usersMapper;

    public LoginResult login(LoginRequest request) throws UnsupportedEncodingException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Users::getUsername,request.getUsername())
                .isNull(Users::getDeletedAt)
                .eq(Users::getStatus,Constant.USERS_STATUS)
                .last(Constant.LIMIT_ONE);
        Users users = usersMapper.selectOne(queryWrapper);
        if (users == null)
            throw new AppException("用户不存在");
        byte[] decode = Base64.getDecoder().decode(users.getPassword());
        String password = new String(decode, StandardCharsets.UTF_8);
        if (!request.getPassword().equals(password))
            throw new AppException("密码错误！");
        Map<String,Object> map = new HashMap<>();
        map.put("userId",users.getId());
        String token = jwtUtils.getToken(map);
        return LoginResult.builder()
                .token(token)
                .build();
    }



}
